<?php

class Common {

	/**
	 * $param 变量
	 * @return void
	 */
	public static function debug() {
		echo '<pre>';
		foreach (func_get_args() as $v) {
			print_r($v);
			echo "\n";
		}
		echo '</pre>';
		exit;
	}

	/**
	 * 获取当前 Path 的 URI
	 * @param $path
	 * @return string
	 */
	public static function getURI($path) {
		return $_SERVER['SCRIPT_NAME'] . $path;
	}

	/**
	 * 获取当前 API Path 的 URI
	 * @param $path
	 * @return string
	 */
	public static function getAPIURI($path) {
		return $_SERVER['SCRIPT_NAME'] . '/plugin' . $path;
	}

	/**
	 * 获取当前 API Path 的静态 URI
	 * @param $path
	 * @return string
	 */
	public static function getAPIStaticURI($path) {
		if ($_SERVER['SCRIPT_NAME'] == '/index.php') {
			return $path;
		}
		return dirname($_SERVER['SCRIPT_NAME']) . $path;
	}

	/**
	 * 获取随机字符、数字
	 * @param $length
	 * @param $numeric
	 * @return string
	 */
	public static function random($length, $numeric = 0) {
		$seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
		$seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
		if ($numeric) {
			$hash = '';
		} else {
			$hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
			$length--;
		}
		$max = strlen($seed) - 1;
		for ($i = 0; $i < $length; $i++) {
			$hash .= $seed[mt_rand(0, $max)];
		}
		return $hash;
	}

	/**
	 * 字符串输出前的转义
	 * @param $string
	 * @param $flags
	 * @return array|mixed|string|string[]
	 */
	public static function htmlspecialchars($string, $flags = null) {
		if (is_array($string)) {
			foreach ($string as $key => $val) {
				$string[$key] = self::htmlspecialchars($val, $flags);
			}
		} else {
			if ($flags === null) {
				$string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
			} else {
				$charset = 'UTF-8';
				$string = htmlspecialchars($string, $flags, $charset);
			}
		}
		return $string;
	}

	/**
	 * 执行内存缓存命令
	 * @param $cmd string Cmd
	 * @param $key
	 * @param $value
	 * @param $ttl
	 * @return bool|mixed|null
	 */
	public static function memory($cmd, $key = '', $value = '', $ttl = 0) {
		$class = 'Memory_Redis';
		$m = new $class();
		if (!$m->env()) {
			return null;
		}
		$argv = func_get_args();
		array_shift($argv);
		$return = null;
		switch ($cmd) {
			case 'set':
				$return = $m->set($key, $value, $ttl);
				break;
			case 'get':
				$return = $m->get($key);
				break;
			case 'rm':
				$return = $m->rm($key);
				break;
			case 'inc':
				$return = $m->inc($key, $value ?: 1);
				if ($ttl > 0) {
					$m->expire($key, $ttl);
				}
				break;
			case 'dec':
				$return = $m->dec($key, $value ?: -1);
				if ($ttl > 0) {
					$m->expire($key, $ttl);
				}
				break;
			default:
				if (!method_exists($m, $c)) {
					return null;
				}
				$return = call_user_func_array(array($m, $c), $argv);
		}
		return $return;
	}

}